package com.lxs.mall.product.service.impl;

import com.lxs.common.utils.PageUtils;
import com.lxs.common.utils.Query;
import com.lxs.mall.product.service.CategoryBrandRelationService;
import com.lxs.mall.product.vo.Catalog2VO;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.constraints.SafeHtml;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.lxs.mall.product.dao.CategoryDao;
import com.lxs.mall.product.entity.CategoryEntity;
import com.lxs.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryPageTrees(Map<String, Object> params) {
        //1，查询商品的所有的分类信息
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2,将商品分类信息拆分成树形结构数据
        List<CategoryEntity> list = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0).map(
                categoryEntity -> {
                    categoryEntity.setChildren(getCatagoryChildrens(categoryEntity, categoryEntities));
                    return categoryEntity;
                }
        ).sorted((cataEntity1, cataEntity2) -> {
            return (cataEntity1.getSort() == null ? 0 : cataEntity1.getSort()) - (cataEntity2.getSort() == null ? 0 : cataEntity2.getSort());
        }).collect(Collectors.toList());
        //2.1,遍历出所有的大类
        //2.2,根据大类找到对应的小类
        return list;
    }

    @Override
    public void removeLogicByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    @Transactional
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if(StringUtils.isNotEmpty(category.getName())){
            categoryBrandRelationService.updateCatalogName(category.getCatId(),category.getName());
        }
    }

    @Override
    public List<CategoryEntity> getLeve1Category() {
        //查询数据库操作
        long start = System.currentTimeMillis();
        List<CategoryEntity>list = baseMapper.queryCategoryLevel1();
        return list;
    }
    @Override
    public Map<String, List<Catalog2VO>> getCatalog2JSON() {
        //查询所有分类数据
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>());
        //获取所有一级分类数据
        List<CategoryEntity> level1Category= this.queryByParenCid(categoryEntities,0l);
        //把一级分类的数据转换为map容器，key就是一级分类的编号，value就是一级分类对应的二级分类数据
        Map<String, List<Catalog2VO>> map = level1Category.stream().collect(Collectors.toMap(
                key -> key.getCatId().toString()
                , value -> {
                    //根据一级编号查询出对应的二级分类数据
                    List<CategoryEntity> l2Catalogs = this.queryByParenCid(categoryEntities, value.getCatId());
                    List<Catalog2VO> l2CatalogVOs = null;
                    if (l2Catalogs != null) {
                       l2CatalogVOs = l2Catalogs.stream().map(l2 -> {
                            //需要把查询出来的数据封装到二级l2CatalogVOs中
                            Catalog2VO catalog2VO = new Catalog2VO(l2.getParentCid().toString(), null, l2.getCatId().toString(), l2.getName());
                            //根据二级分类编号找到对应的三级分类信息
                            List<CategoryEntity> l3CatalogVOs = this.queryByParenCid(categoryEntities, l2.getCatId());
                            if (l3CatalogVOs != null) {
                                //根据二级分类数据找到对应的三级分类数据
                                List<Catalog2VO.Catalog3VO> catalog3VOS = l3CatalogVOs.stream().map(l3 -> {
                                    Catalog2VO.Catalog3VO catalog3VO = new Catalog2VO.Catalog3VO(l3.getParentCid().toString(), l3.getCatId().toString(), l3.getName());
                                    return catalog3VO;
                                }).collect(Collectors.toList());
                                // 三级分类关联二级分类
                                catalog2VO.setCatalog3List(catalog3VOS);
                            }
                            return catalog2VO;
                        }).collect(Collectors.toList());

                    }
                    return l2CatalogVOs;
                }
                ));
        return map;
    }
    /**
     * 跟进父编号获取对应的子菜单信息
     * @param list
     * @param parentCid
     * @return
     */
    private List<CategoryEntity> queryByParenCid(List<CategoryEntity> list,Long parentCid){
        List<CategoryEntity> collect = list.stream().filter(item -> {
            return item.getParentCid().equals(parentCid);
        }).collect(Collectors.toList());
        return collect;
    }
    /**
     * 225,22,2
     * @param catelogId
     * @param paths
     * @return
     */
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if(entity.getParentCid() != 0){
            findParentPath(entity.getParentCid(),paths);
        }
        return paths;
    }
    private List<CategoryEntity> getCatagoryChildrens(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(entity -> {
            return entity.getParentCid().equals(categoryEntity.getCatId());
        }).map(entity -> {
            entity.setChildren(getCatagoryChildrens(entity, categoryEntities));
            return entity;
        }).sorted((cataEntity1, cataEntity2) -> {
            return (cataEntity1.getSort() == null ? 0 : cataEntity1.getSort()) - (cataEntity2.getSort() == null ? 0 : cataEntity2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}
